﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

using QuickTuner.Properties;
using QuickTuner.Util;

namespace QuickTuner
{
    public partial class editForm : Form
    {
        private readonly StationList _list;

        public static bool InstanceRunning { get; set; }

        public editForm(StationList theList)
        {
            InstanceRunning = true;

            InitializeComponent();

            this.Icon = Resources.editFormIcon;
            this.Location = Program.Config.editFormLocation;
            this.Size = Program.Config.editFormSize;

            stationsSource.DataSource = _list = theList;
        }

        // Event handlers _______________________________________________________________

        private void addButton_Click(object sender, EventArgs e) { stationsSource.AddNew(); }

        private void deleteButton_Click(object sender, EventArgs e) { stationsSource.RemoveCurrent(); }

        private void importListButton_Click(object sender, EventArgs e)
        {
            // load saved path or default to my documents
            var path = Program.Config.lastOpenPath;
            if (string.IsNullOrEmpty(path))
                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            openDialog.InitialDirectory = path;

            // show the open file dialog
            if (openDialog.ShowDialog() == DialogResult.Cancel) return;

            // save the path settings
            Program.Config.lastOpenPath = Path.GetDirectoryName(openDialog.FileName);

            // load list of stations from the selected file
            var fs = File.OpenRead(openDialog.FileName);

            var importList = StationList.LoadFrom(fs);

            fs.Close();
            fs.Dispose();

            foreach (var station in importList)
                stationsSource.Add(station);
        }

        private void exportListButton_Click(object sender, EventArgs e)
        {
            // load saved path or default to my documents
            var path = Program.Config.lastSavePath;
            if (string.IsNullOrEmpty(path))
                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            saveDialog.InitialDirectory = path;

            // show the save file dialog
            if (saveDialog.ShowDialog() == DialogResult.Cancel) return;

            // save the path settings
            Program.Config.lastSavePath = Path.GetDirectoryName(saveDialog.FileName);

            // save list of stations to selected file
            var fs = File.OpenWrite(saveDialog.FileName);

            _list.SaveTo(fs);

            fs.Close();
            fs.Dispose();
        }

        private void saveButton_Click(object sender, EventArgs e) { this.Close(); }

        private void editForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // make sure any editing progress is commited before closing the form
            if (stationsGrid.IsCurrentCellInEditMode)
                stationsGrid.EndEdit();
        }

        private void stationsSource_AddingNew(object sender, AddingNewEventArgs e) { e.NewObject = new Station(); }

        private void stationsGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var emptyImage = Resources.musicImage;

            foreach (DataGridViewRow row in stationsGrid.Rows)
            {
                // get the row's attached station
                var station = row.DataBoundItem as Station;
                if (station == null) return;

                // get the first cell
                var cell = (DataGridViewImageCell)row.Cells[0];

                // assign the "empty" image first in case a favicon is not found.
                cell.Value = emptyImage;

                // download image and if success, use it as the icon
                IconCache.BeginGetIcon(station, ar => {
                    var img = IconCache.EndGetIcon(ar);
                    if (img != null) cell.Value = img;

                });

                Application.DoEvents();
            }
        }

        private void editForm_FormClosed(object sender, FormClosedEventArgs e) { InstanceRunning = false; }

        private void shareListButton_Click(object sender, EventArgs e) { }

        private void gotoWebsiteButton_Click(object sender, EventArgs e) { Process.Start(@"http://quicktuner.net/"); }
    }
}